<template>
    <!-- 对话框表单 -->
    <!-- 建议使用 Prettier 格式化代码 -->
    <!-- el-form 内可以混用 el-form-item、FormItem、ba-input 等输入组件 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        width="50%"
        :destroy-on-close="true"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '':'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="{...baTable.form.items, ...baTable.form.extend!.field}"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <FormItem
                        :label="t('workorder.fields.position')"
                        type="radio"
                        v-model="baTable.form.items!.position"
                        prop="position"
                        :data="{
                            content: {
                                wo: '案件提交',
                                //user: t('workorder.fields.position user'),
                                //engineer: '工程师反馈',
                                initial: '初步分析',
                                detailed: '深入分析',
                            },
                        }"
                        :placeholder="t('Please select field', { field: t('workorder.fields.position') })"
                    />
                    <CreateFormItemData dataTitle="字段" v-model="baTable.form.extend!.field" />
                    <FormItem
                        :label="t('workorder.fields.default')"
                        type="string"
                        v-model="baTable.form.items!.default"
                        prop="default"
                        placeholder="可以直接输入null、0、empty string"
                    />
                    <FormItem
                        :label="t('workorder.fields.error_msg')"
                        type="textarea"
                        v-model="baTable.form.items!.error_msg"
                        prop="error_msg"
                        :input-attr="{ rows: 3 }"
                        @keyup.enter.stop=""
                        @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                        placeholder="留空则自动填写验证器的 title 属性，不理解请直接忽略"
                    />
                    <FormItem
                        v-if="baTable.form.items!.position == 'wo'"
                        label="自动填充"
                        type="switch"
                        v-model="baTable.form.items!.autofill"
                        prop="autofill"
                        :data="{ content: { '0': '关', '1': '开' } }"
                        :attr="{
                            blockHelp: '自动从会员信息和上次工单信息中提取当前字段值进行填充',
                        }"
                    />
                    <FormItem
                        v-if="baTable.form.items!.position == 'wo'"
                        :label="t('workorder.fields.basic_info')"
                        type="switch"
                        v-model="baTable.form.items!.basic_info"
                        prop="basic_info"
                        :data="{ content: { '0': t('workorder.fields.basic_info 0'), '1': t('workorder.fields.basic_info 1') } }"
                        :attr="{
                            blockHelp: '作为工单的基本信息，这类字段将在工单详情中显示',
                        }"
                    />
                    <FormItem
                        v-if="baTable.form.items!.position == 'wo'"
                        label="工单沟通消息"
                        type="switch"
                        v-model="baTable.form.items!.message"
                        prop="message"
                        :data="{ content: { '0': '关', '1': '开' } }"
                        :attr="{
                            blockHelp: '作为工单的沟通消息字段，此字段将在用户提交工单时，自动作为工单的沟通记录',
                        }"
                    />
                    <FormItem
                        v-if="baTable.form.items!.position == 'wo'"
                        :label="t('workorder.fields.backend_show')"
                        type="switch"
                        v-model="baTable.form.items!.backend_show"
                        prop="backend_show"
                        :data="{ content: { '0': t('workorder.fields.backend_show 0'), '1': t('workorder.fields.backend_show 1') } }"
                        :attr="{
                            blockHelp: '在后台的工单管理表格中显示此字段',
                        }"
                    />
                    <FormItem
                        v-if="baTable.form.items!.position == 'wo'"
                        :label="t('workorder.fields.backend_com_search')"
                        type="switch"
                        v-model="baTable.form.items!.backend_com_search"
                        prop="backend_com_search"
                        :data="{ content: { '0': t('workorder.fields.backend_com_search 0'), '1': t('workorder.fields.backend_com_search 1') } }"
                        :attr="{
                            blockHelp: '后台的工单管理表格可以通过此字段进行公共搜索',
                        }"
                    />
                    <FormItem
                        v-if="baTable.form.items!.position == 'wo'"
                        :label="t('workorder.fields.backend_sort')"
                        type="switch"
                        v-model="baTable.form.items!.backend_sort"
                        prop="backend_sort"
                        :data="{ content: { '0': t('workorder.fields.backend_sort 0'), '1': t('workorder.fields.backend_sort 1') } }"
                        :attr="{
                            blockHelp: '后台的工单管理表格可以通过此字段排序',
                        }"
                    />
                    <FormItem
                        v-if="baTable.form.items!.position == 'wo'"
                        :label="t('workorder.fields.backend_column_attr')"
                        type="textarea"
                        v-model="baTable.form.items!.backend_column_attr"
                        prop="backend_column_attr"
                        :input-attr="{ rows: 3 }"
                        @keyup.enter.stop=""
                        @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                        placeholder="后台工单管理表格字段额外属性，一行一个，无需引号，比如：width=100、render=image"
                    />
                    <FormItem
                        label="字段完整类型"
                        type="string"
                        prop="data_type"
                        v-model="baTable.form.items!.data_type"
                        :attr="{
                            blockHelp: '指当前字段在工单表的实际类型，在上方选择字段类型后，本完整类型将自动生成，若无必要无需修改',
                        }"
                    />
                    <FormItem
                        :label="t('workorder.fields.weigh')"
                        type="number"
                        prop="weigh"
                        :input-attr="{ step: 1 }"
                        v-model.number="baTable.form.items!.weigh"
                        :placeholder="t('Please input field', { field: t('workorder.fields.weigh') })"
                    />
                    <FormItem
                        :label="t('workorder.fields.status')"
                        type="switch"
                        v-model="baTable.form.items!.status"
                        prop="status"
                        :data="{ content: { '0': t('workorder.fields.status 0'), '1': t('workorder.fields.status 1') } }"
                    />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import { inject, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'
import CreateFormItemData from '/@/components/formItem/createData.vue'
import { fieldData } from '/@/components/baInput/helper'

const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    name: [buildValidatorData({ name: 'required', title: '字段名' }), buildValidatorData({ name: 'varName', title: '请以变量命名规则填写字段名' })],
    title: [buildValidatorData({ name: 'required', title: '字段标题' })],
    type: [buildValidatorData({ name: 'required', title: '字段类型' })],
    data_type: [buildValidatorData({ name: 'required', title: '字段完整类型' })],
    update_time: [buildValidatorData({ name: 'date', title: t('workorder.fields.update_time') })],
    create_time: [buildValidatorData({ name: 'date', title: t('workorder.fields.create_time') })],
})

watch(
    () => baTable.form.extend!.field,
    (field) => {
        if (!field.type) return
        if (baTable.form.extend!.dataEbak && field.type == baTable.form.extend!.dataEbak.type && field.dict == baTable.form.extend!.dataEbak.dict) {
            baTable.form.items!.data_type = baTable.form.extend!.dataEbak.data_type
            return
        }
        if (fieldData[field.type].length > 0) {
            baTable.form.items!.data_type = `${fieldData[field.type].type}(${fieldData[field.type].length})`
        } else if (['enum', 'set'].includes(fieldData[field.type].type)) {
            let dict: string[] = field.dict ? field.dict.split(/[(\r\n)\r\n]+/) : []
            dict = dict
                .map((value) => {
                    if (!value) return ''
                    let temp = value.split('=')
                    if (temp[0] && temp[1]) {
                        return `'${temp[0]}'`
                    }
                    return ''
                })
                .filter((str: string) => str != '')
            baTable.form.items!.data_type = `${fieldData[field.type].type}(${dict.join(',')})`
        } else if (fieldData[field.type].length <= 0) {
            baTable.form.items!.data_type = `${fieldData[field.type].type}`
        } else {
            baTable.form.items!.data_type = `varchar(255)`
        }
    }
)
</script>

<style scoped lang="scss"></style>
